<?php

/**
 * @author James Hartig
 * @copyright 2010
 */

class gsRecent{
	
	private static $rss_url = "http://api.grooveshark.com/feeds/1.0/users/%s/%s.rss"; //format of user and then method
	
	function __construct(){}
	
	public static function getRecentListens($username,$limit=10,$cache=true){
		if (preg_match("/^([A-Za-z0-9]){3,20}$/",$username) === false)
			return false;
		
		/*if ($cache){
			
		}*/
		//default to gsapi
		$rss = self::httpCall(sprintf(self::$rss_url,$username,'recent_listens'));
			
		return self::parseRSS($rss['raw'],$limit);			
	}
	
	public static function getUniqueRecentSongs($songs,$limit=10,$period=1800){
		//the songs should be in decending order with the newest song at [0]
		//by default the following code will remove any duplicate songs  (as determined if the song period is < $period  (seconds))
		$titles = array(); //our title container
		$endSongs = array(); //I would have used unset below but using another container I can easily incorporate the limit into the foreach as well
		foreach($songs AS $song){
			if (isset($song['title'])){ //only if we have a title
				if ((!isset($titles[$song['title']]) || $titles[$song['title']]-$period >= $song['pubTime']) && $song != end($endSongs)){ //if we have not processed the title or the last play was > $period ago
					$titles[$song['title']] = $song['pubTime']; //set the new pubTime
					$endSongs[] = $song;
				}
			}else
				$endSongs[] = $song; //we should still add it

			if ($limit>0 && count($endSongs) == $limit)
				break;
		}
		return $endSongs;
	}
	
	public static function getRecentFavorites($username,$limit=10,$cache=true){
		if (preg_match("/^([A-Za-z0-9]){3,20}$/",$username) === false)
			return false;
		
		/*if ($cache){
			
		}*/
		$rss = self::httpCall(sprintf(self::$rss_url,$username,'recent_favorite_songs'));
			
		return self::parseRSS($rss['raw'],$limit);				
	}
	
	//function that compares the recent list (in the format provided by getRecentFavorites) to the current Favorites, provided in the song format
	public static function limitRecentFavoritesToCurrent($recent,$favorites){
		return $recent;
	}
	
	//modified version from deVolf	
	private static function parseRSS($rss,$limit=0){
    	if (preg_match_all("|<item[^>]*>(.*?)</item>|ixs",$rss,$matches) == 0)
    		return array(); //there were no songs found
    	$entries = $matches[1];
    	unset($matches,$data);
		$data = array();
		$times = array(); //used for sorting
    	foreach($entries AS $entry){
    		if ($limit<1 || $limit > count($data)){
				if(preg_match_all("/\<([a-zA-Z]+)\>(.*?)(?:\<\/\\1\>)/ixs", $entry, $matches)){
					$tmp = array();
					foreach($matches[1] AS $k => $tag)
						$tmp[$tag] = (isset($matches[2][$k]) ? $matches[2][$k] : "");
					
					if (isset($tmp['pubDate'])){ //little hack
						$tmp['pubTime'] = strtotime($tmp['pubDate']);
						//add time to our sorting times array
						$times[$tmp['pubTime']] = count($data); //store the key //since we are adding the value after this we don't do -1
					}
					
					$data[] = $tmp;
				}
			}else
				break;
		}
		
		if (count($times)>1){
			$data2 = array(); //our final container array
			krsort($times);
			foreach($times AS $key)
				$data2[] = $data[$key];
			unset($data,$times);
			$data = $data2;
		}
		
		return $data;
    }
    
    public static function getSongDetails($songs){
    	if (!class_exists("gsapi"))
    		return false;
    	
    	foreach($songs AS &$song){
    		list($title, $artist) = explode(" - ",$song['title'],2);
    		$song = array_merge($song,gsapi::tinysongApiSongDetailsAdv($title,$artist));
   		}
   		return $songs;
    }
	
	private static function httpCall($url){
		if (empty($url))
			return false;
			
	    $c = curl_init();
	    curl_setopt($c, CURLOPT_URL, $url);
	    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 4);
	    curl_setopt($c, CURLOPT_USERAGENT, 'fastest963-GSAPI-PHP');
	    $result = curl_exec($c);
	    $code = curl_getinfo($c, CURLINFO_HTTP_CODE);
	    $size = curl_getinfo($c, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
	    $type = curl_getinfo($c, CURLINFO_CONTENT_TYPE);
	    curl_close($c);	
	    return array('http'=>$code,'raw'=>$result,'size'=>$size,'type'=>$type);
	}
}

?>